package com.ruoyi.project.cardbox.orders.service.impl;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.project.cardbox.inbound.domain.OrderInbound;
import com.ruoyi.project.cardbox.inbound.mapper.OrderInboundMapper;
import com.ruoyi.project.cardbox.inbound.service.IOrderInboundService;
import com.ruoyi.project.cardbox.orders.domain.OrderStatus;
import com.ruoyi.project.cardbox.orders.domain.OrdersBO;
import com.ruoyi.project.cardbox.orders.domain.OrdersVO;
import com.ruoyi.project.cardbox.outbound.domain.OrderOutbound;
import com.ruoyi.project.cardbox.outbound.mapper.OrderOutboundMapper;
import com.ruoyi.project.cardbox.outbound.service.IOrderOutboundService;
import com.ruoyi.project.cardbox.request.domain.OrderRequest;
import com.ruoyi.project.cardbox.request.mapper.OrderRequestMapper;
import com.ruoyi.project.cardbox.request.service.IOrderRequestService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.project.cardbox.orders.mapper.OrdersMapper;
import com.ruoyi.project.cardbox.orders.domain.Orders;
import com.ruoyi.project.cardbox.orders.service.IOrdersService;
import com.ruoyi.common.utils.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 主订单Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-04
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders>  implements IOrdersService
{
    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private OrderRequestMapper orderRequestMapper;
    @Autowired
    private OrderInboundMapper orderInboundMapper;
    @Autowired
    private OrderOutboundMapper orderOutboundMapper;
    @Autowired
    private IOrderRequestService orderRequestService;
    @Autowired
    private IOrderInboundService orderInboundService;
    @Autowired
    private IOrderOutboundService orderOutboundService;

    /**
     * 查询主订单
     * 
     * @param id 主订单主键
     * @return 主订单
     */
    @Override
    public Orders selectOrdersById(Long id)
    {
        return ordersMapper.selectOrdersById(id);
    }

    /**
     * 查询主订单列表
     * 
     * @param orders 主订单
     * @return 主订单
     */
    @Override
    public List<Orders> selectOrdersList(Orders orders)
    {
        return ordersMapper.selectOrdersList(orders);
    }

    /**
     * 新增主订单
     * 
     * @param orders 主订单
     * @return 结果
     */
    @Override
    public int insertOrders(Orders orders)
    {
        //先判断订单号是否已存在
        if(ordersMapper.selectOrdersByOrderId(orders.getOrderId()) != null){
            throw new ServiceException("订单号已存在");
        }
        if(orders.getBoxQuantity() < 0){
            throw new ServiceException("纸箱订单量不能小于0");
        }
        if (orders.getTax() == null
                || orders.getTax().compareTo(BigDecimal.ZERO) < 0
                || orders.getTax().compareTo(BigDecimal.valueOf(100)) > 0) {
            throw new ServiceException("税率不能为空，且必须在 0 ~ 100 之间");
        }
        if(orders.getProcessingFee()== null){
            orders.setProcessingFee(BigDecimal.ZERO);
        }

        orders.setCreateTime(DateUtils.getNowDate());
        orders.setUpdateTime(DateUtils.getNowDate());
        orders.setStatus(OrderStatus.DRAFT);
        return ordersMapper.insertOrders(orders);
    }

    /**
     * 修改主订单
     * 
     * @param ordersVO 主订单
     * @return 结果
     */
    @Override
    public int updateOrders(OrdersVO ordersVO)
    {
        Orders orders = new Orders();
        orders.setId(ordersVO.getId());
        orders.setCustomerName(ordersVO.getCustomerName());
        orders.setProductName(ordersVO.getProductName());
        if(ordersVO.getBoxQuantity() != null&& ordersVO.getBoxQuantity() < 0){
            throw new ServiceException("纸箱订单量不能小于0");
        }
        orders.setBoxQuantity(ordersVO.getBoxQuantity());
        if (ordersVO.getProcessingFee() == null) {
            orders.setProcessingFee(BigDecimal.ZERO);
        }else {
            orders.setProcessingFee(ordersVO.getProcessingFee());
        }
        orders.setTax(ordersVO.getTax());
        orders.setUpdateTime(DateUtils.getNowDate());

        return ordersMapper.updateById(orders);
    }

    /**
     * 批量删除主订单
     * 
     * @param ids 需要删除的主订单主键
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteOrdersByIds(String ids) {
        String[] idArray = Convert.toStrArray(ids);

        for (String idStr : idArray) {
            Long id = Long.parseLong(idStr);

            // 1. 查询主订单
            Orders order = ordersMapper.selectOrdersById(id);
            if (order != null) {
                String orderId = order.getOrderId();

                // 2. 删除子表：出库
                LambdaQueryWrapper<OrderOutbound> outboundWrapper = new LambdaQueryWrapper<>();
                outboundWrapper.eq(OrderOutbound::getOrderId, orderId);
                orderOutboundService.remove(outboundWrapper); // 删除所有匹配项

                // 3. 删除子表：入库
                LambdaQueryWrapper<OrderInbound> inboundWrapper = new LambdaQueryWrapper<>();
                inboundWrapper.eq(OrderInbound::getOrderId, orderId);
                orderInboundService.remove(inboundWrapper);

                // 4. 删除子表：请购单
                LambdaQueryWrapper<OrderRequest> requestWrapper = new LambdaQueryWrapper<>();
                requestWrapper.eq(OrderRequest::getOrderId, orderId);
                orderRequestService.remove(requestWrapper);
            }
        }

        // 5. 最后统一删除主订单
        return ordersMapper.deleteOrdersByIds(idArray);
    }



    /**
     * 删除主订单信息
     * 
     * @param id 主订单主键
     * @return 结果
     */
    @Override
    public int deleteOrdersById(Long id)
    {
        return ordersMapper.deleteOrdersById(id);
    }

    @Override
    public int updateOrdersStatus(Long id) {
        //先判断是否存在
        Orders order = ordersMapper.selectOrdersById(id);
        if(order== null){
            throw new ServiceException("订单不存在");
        }
        OrderStatus currentStatus = order.getStatus();
        if (currentStatus == OrderStatus.OUT_STOCK) {
            throw new ServiceException("订单已出库，状态不可更改");
        }
        OrderStatus nextStatus = getNextStatus(currentStatus);
        // 先创建对应子表，成功后再更新状态
        switch (nextStatus) {
            case REQUESTED:
                orderRequestService.createOrderRequest(order);
                break;
            case IN_STOCK:
                orderInboundService.createInboundReceipt(order);
                break;
            case OUT_STOCK:
                orderOutboundService.createOutboundReceipt(order);
                break;
            default:
                throw new ServiceException("状态转换异常");
        }

        // 子表插入成功后再更新状态
        order.setStatus(nextStatus);
        boolean updated = this.updateById(order);
        if (!updated) {
            throw new ServiceException("状态更新失败");
        }

        return 1;
    }
    @Override
    public List<OrdersBO> selectOrdersBOList(Orders orders) {
        List<Orders> ordersList = ordersMapper.selectOrdersList(orders);
        List<OrdersBO> result = new ArrayList<>();

        for (Orders o : ordersList) {
            OrdersBO bo = new OrdersBO();
            BeanUtils.copyProperties(o, bo);
            String orderId = o.getOrderId();
            int statusValue = o.getStatus() != null ? o.getStatus().getValue() : -1;
            bo.setStatus(o.getStatus());

            BigDecimal cardBoardPrice = BigDecimal.ZERO;
            BigDecimal batchProfit = BigDecimal.ZERO;

            // 1. 请购数据
            if (statusValue >= OrderStatus.REQUESTED.getValue()) {
                LambdaQueryWrapper<OrderRequest> requestWrapper = new LambdaQueryWrapper<>();
                requestWrapper.eq(OrderRequest::getOrderId, orderId);
                OrderRequest request = orderRequestService.getOne(requestWrapper);

                if (request != null) {
                    Long quantity = request.getOrderQuantity() != null ? request.getOrderQuantity() : 0L;
                    BigDecimal area = request.getArea() != null ? request.getArea() : BigDecimal.ZERO;
                    BigDecimal unitPrice = request.getUnitPrice() != null ? request.getUnitPrice() : BigDecimal.ZERO;

                    bo.setCardboardQuantity(quantity);
                    bo.setCardboardArea(area);
                    cardBoardPrice = unitPrice.multiply(BigDecimal.valueOf(quantity));
                    bo.setCardboardPrice(cardBoardPrice.setScale(2, RoundingMode.HALF_UP));
                }
            }

            // 2. 入库数据
            if (statusValue >= OrderStatus.IN_STOCK.getValue()) {
                LambdaQueryWrapper<OrderInbound> inboundWrapper = new LambdaQueryWrapper<>();
                inboundWrapper.eq(OrderInbound::getOrderId, orderId);
                OrderInbound inbound = orderInboundService.getOne(inboundWrapper);

                if (inbound != null) {
                    Long quantity = inbound.getQuantity() != null ? inbound.getQuantity() : 0L;
                    BigDecimal unitPrice = inbound.getUnitPrice() != null ? inbound.getUnitPrice() : BigDecimal.ZERO;

                    bo.setInCardboardQuantity(quantity);
                    cardBoardPrice = unitPrice.multiply(BigDecimal.valueOf(quantity));
                    bo.setCardboardPrice(cardBoardPrice.setScale(2, RoundingMode.HALF_UP));
                }
            }

            // 3. 出库数据
            if (statusValue >= OrderStatus.OUT_STOCK.getValue()) {
                LambdaQueryWrapper<OrderOutbound> outboundWrapper = new LambdaQueryWrapper<>();
                outboundWrapper.eq(OrderOutbound::getOrderId, orderId);
                OrderOutbound outbound = orderOutboundService.getOne(outboundWrapper);

                if (outbound != null) {
                    Long quantity = outbound.getQuantity() != null ? outbound.getQuantity() : 0L;
                    BigDecimal area = outbound.getArea() != null ? outbound.getArea() : BigDecimal.ZERO;
                    BigDecimal profit = outbound.getProfit() != null ? outbound.getProfit() : BigDecimal.ZERO;
                    BigDecimal amount = outbound.getAmount() != null ? outbound.getAmount() : BigDecimal.ZERO;
                    BigDecimal carriage = outbound.getCarriage() != null ? outbound.getCarriage() : BigDecimal.ZERO;

                    bo.setOutBoxQuantity(quantity);
                    bo.setBoxArea(area.multiply(BigDecimal.valueOf(quantity)));
                    bo.setProfit(profit);

                    BigDecimal processingFee = o.getProcessingFee() != null
                            ? o.getProcessingFee().multiply(BigDecimal.valueOf(quantity))
                            : BigDecimal.ZERO;
                    BigDecimal tax = o.getTax() != null
                            ? o.getTax().divide(BigDecimal.valueOf(100), 4, RoundingMode.HALF_UP)
                            : BigDecimal.ZERO;

                    batchProfit = amount
                            .subtract(cardBoardPrice)
                            .subtract(carriage)
                            .subtract(processingFee)
                            .multiply(BigDecimal.ONE.subtract(tax));
                    bo.setBatchProfit(batchProfit.setScale(2, RoundingMode.HALF_UP));

                    // 计算剩余面积（安全减法）
                    BigDecimal cardboardArea = bo.getCardboardArea() != null ? bo.getCardboardArea() : BigDecimal.ZERO;
                    BigDecimal boxArea = bo.getBoxArea() != null ? bo.getBoxArea() : BigDecimal.ZERO;
                    bo.setRemainingArea(cardboardArea.subtract(boxArea).max(BigDecimal.ZERO));
                }
            }

            result.add(bo);
        }

        return result;
    }



//    @Override
//    public List<OrdersBO> selectOrdersBOList(Orders orders) {
//        // 先查出 orders 基础信息
//        List<Orders> ordersList = ordersMapper.selectOrdersList(orders);
//        List<OrdersBO> result = new ArrayList<>();
//        for (Orders o : ordersList) {
//            OrdersBO bo = new OrdersBO();
//            BeanUtils.copyProperties(o, bo);
//            String orderId = o.getOrderId();
//            int statusValue = o.getStatus() != null ? o.getStatus().getValue() : -1;
//            bo.setStatus(o.getStatus()); // 会自动设置 statusStr
//            //整批外购纸板价格
//            BigDecimal cardBoardPrice = BigDecimal.ZERO;
//            //整批利润
//            BigDecimal batchProfit = BigDecimal.ZERO;
//
//            if (statusValue >= OrderStatus.REQUESTED.getValue()){
//                LambdaQueryWrapper<OrderRequest> requestWrapper = new LambdaQueryWrapper<>();
//                requestWrapper.eq(OrderRequest::getOrderId, orderId);
//                OrderRequest request = orderRequestService.getOne(requestWrapper);
//
//                //纸板订单量
//                bo.setCardboardQuantity(request.getOrderQuantity());
//                //整批纸板面积
//                bo.setCardboardArea(request.getArea());
//                //整批外购纸板价格
//                cardBoardPrice =request.getUnitPrice().multiply(BigDecimal.valueOf(request.getOrderQuantity()));
//                bo.setCardboardPrice(cardBoardPrice);
//            }
//            // 2. 入库数据
//            if (statusValue >= OrderStatus.IN_STOCK.getValue()) {
//                LambdaQueryWrapper<OrderInbound> inboundWrapper = new LambdaQueryWrapper<>();
//                inboundWrapper.eq(OrderInbound::getOrderId, orderId);
//                OrderInbound inbound = orderInboundService.getOne(inboundWrapper);
//                //纸板入库数量
//                bo.setInCardboardQuantity(inbound.getQuantity());
//                //整批外购纸板价格
//                cardBoardPrice =inbound.getUnitPrice().multiply(BigDecimal.valueOf(inbound.getQuantity()));
//                bo.setCardboardPrice(cardBoardPrice);
//            }
//            // 3. 出库数据
//            if (statusValue >= OrderStatus.OUT_STOCK.getValue()) {
//                LambdaQueryWrapper<OrderOutbound> outboundWrapper = new LambdaQueryWrapper<>();
//                outboundWrapper.eq(OrderOutbound::getOrderId, orderId);
//                OrderOutbound outbound = orderOutboundService.getOne(outboundWrapper);
//                //纸箱出库数量
//                bo.setOutBoxQuantity(outbound.getQuantity());
//                //整批纸箱面积
//                bo.setBoxArea(outbound.getArea().multiply(BigDecimal.valueOf(outbound.getQuantity())));
//                //单个纸箱利润
//                bo.setProfit(outbound.getProfit());
//                //整批利润
//                batchProfit=(outbound.getAmount().subtract(cardBoardPrice).subtract(outbound.getCarriage()).subtract(o.getProcessingFee().multiply(BigDecimal.valueOf(outbound.getQuantity())))).multiply(1-o.getTax().divide(new BigDecimal(100)));
//                bo.setBatchProfit(batchProfit);
//            }
//
//
//            result.add(bo);
//        }
//        return result;
//
//    }

    private OrderStatus getNextStatus(OrderStatus current) {
        switch (current) {
            case DRAFT:
                return OrderStatus.REQUESTED;
            case REQUESTED:
                return OrderStatus.IN_STOCK;
            case IN_STOCK:
                return OrderStatus.OUT_STOCK;
            default:
                throw new ServiceException("已是最终状态，无法推进");
        }
    }
}
